<template>
  <div ref="chart" style="width: 600px; height: 400px"></div>
</template>
<script lang="ts" setup>
import { ref, onMounted, defineProps } from "vue";
import { http } from "@/api";
import dayjs from "dayjs";
import { map, get, extend } from "lodash";
import * as echarts from "echarts";
import apiResultConfig from "../chartOptionConfig.json";

interface Props {
  param: any;
}

const props = defineProps<Props>();
const chart = ref(null);

const generateOption = ({ result, configKey }: { result: Array<any>; configKey: string }): any => {
  const { dimensions, chartOption } = apiResultConfig[configKey];

  const data = map(result, item => {
    return map(dimensions, name => get(item, name));
  });

  return extend({}, chartOption, {
    dataset: {
      dimensions, // 定义数据的维度
      source: data // 数据源
    }
  });
};

onMounted(async () => {
  console.log("chart-line", props.param);

  const {
    api: { method, url },
    param
  } = props.param;
  const { result } = await http[method](url, {
    ...param,
    startTime: dayjs(param.startTime).valueOf(),
    endTime: dayjs(param.endTime).valueOf()
  });
  console.log("chart-line-result", result);

  if (chart.value) {
    const myChart = echarts.init(chart.value);

    const option = generateOption({ result, configKey: url });

    myChart.setOption(option);
  }
});
</script>
